
#pragma once
#include"InetAddr.hpp"
#include<string>
#include<iostream>
#include"Log.hpp"
#include<functional>
using namespace std;
using namespace LogModule;

class Reactor;

class Connection
{
public:
    Connection()
    :_sockfd(-1),_events(0)
    {}

    void SetEvents(uint32_t events) //设置关心的事件
    {
         _events = events;
         LOG(LogLevel::DEBUG) << "SetsockEvents success\n";
    }

    uint32_t GetEvents()
    {return _events;}

    // void InitCB( func_t recver, func_t sender, func_t excepter)
    // {
    //        _recver = recver;
    //        _sender = sender;
    //        _excepter = excepter;
    // }

    // void CallRecv()
    // {
    //     if(_recver != nullptr)
    //      _recver();
    // }

    // void CallSend()
    // {
    //     if(_sender != nullptr)
    //       _sender();
    // }

    int Sockfd()
    {
        return _sockfd;
    }

    void SetSockfd(int sockfd)
    {
        _sockfd = sockfd;
        LOG(LogLevel::DEBUG) << "Setsockfd success\n";
    }

    void SetOwner(Reactor* owner)
    {
        _owner = owner;
    }

    Reactor* GetOwner()
    {
        return _owner;
    }

    void SetPeerInfo(const InetAddr& peer_addr)
    {
        _peer_addr = peer_addr;
    }
    void Append(const string& in)
    {
         _inbuffer += in;
    }

    string& Inbuffer() //注意这里是引用 才能在处理消息时剔除已经确认的部分
    {
        return _inbuffer;
    }

    void Close()
    {
        if(_sockfd > 0)
         ::close(_sockfd);
    }

    bool isOutbufferEmpty()
    {
        return _outbuffer.empty();
    }

    void AppendToOut(string& out)
    {
        _outbuffer += out;
    }

    void DiscardOutString(int n)//剔除应答中已经发出去的
    {
        _outbuffer.erase(0,n);
    }

    std::string &OutString() // for test
    {
        return _outbuffer;
    }
    ~Connection()
    {}
    virtual void Sender()=0;
    virtual void Recver()=0;
    virtual void Excepter()=0;//处理异常

protected:
   int _sockfd; //listen还是普通IO都看作一个链接->对应一个fd
   string _inbuffer;
   string _outbuffer;
   InetAddr _peer_addr; //对应哪一个客户端
  //回调方法

  //添加指针
  Reactor* _owner;
  //连接关心的事件
  uint32_t _events;
};
